<template>
  <div>
    <DynamicTable
      row-key="id"
      show-index
      header-title="水表读数管理"
      :data-request="getMeterreadingList"
      :columns="columns"
      bordered
      size="small"
    >
      <template #toolbar>
        <!--        <a-button type="primary" @click="openMenuModal({})"> 新增</a-button>-->
      </template>
    </DynamicTable>
  </div>
</template>

<script lang="ts" setup>
  import { baseColumns, type TableListItem, type TableColumnItem } from './columns';
  import { meterreadingSchemas } from './formSchemas';
  import {
    getMeterreadingList,
    editMeterreading,
    createMeterreading,
    deleteMeterreading,
    getMeterreadingInfo,
  } from '@/api/data/meterreading';
  import { useTable } from '@/components/core/dynamic-table';
  import { useFormModal } from '@/hooks/useModal/useFormModal';

  defineOptions({
    name: 'Meterreading',
  });

  const [DynamicTable, dynamicTableInstance] = useTable();

  const [showModal] = useFormModal();

  /**
   * @description 打开新增/编辑弹窗
   */
  const openMenuModal = async (record: Partial<TableListItem>) => {
    const [formRef] = await showModal<API.UpdateMeterreadingParams>({
      modalProps: {
        title: `${record.id ? '编辑' : '新增'}水表读数`,
        width: '50%',
        onFinish: async (values) => {
          record.id && (values.id = record.id);
          const params = {
            ...values,
          };
          console.log('新增/编辑水表读数', params);
          await (record.id ? editMeterreading : createMeterreading)(params);
          dynamicTableInstance?.reload();
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: meterreadingSchemas,
      },
    });

    //formRef?.updateSchema([]);
    // 如果是编辑的话，需要获取水表读数详情
    if (record.id) {
      const data = await getMeterreadingInfo({ id: record.id });
      formRef?.setFieldsValue({
        ...data,
      });
    }
  };
  const delRowConfirm = async (record: TableListItem) => {
    await deleteMeterreading([record.id]);
    dynamicTableInstance?.reload();
  };

  const columns: TableColumnItem[] = [
    ...baseColumns,
    {
      title: '操作',
      width: 160,
      dataIndex: 'ACTION',
      hideInSearch: true,
      align: 'center',
      fixed: 'right',
      actions: ({ record }) => [
        // {
        //   label: '编辑',
        //   onClick: () => openMenuModal(record),
        // },
        {
          label: '删除',
          popConfirm: {
            title: '你确定要删除吗？',
            onConfirm: () => delRowConfirm(record),
          },
        },
      ],
    },
  ];
</script>
